package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.SystemArticleManager;
import com.fish.anne.model.SystemArticle;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class SystemArticleAction extends BaseAction implements Preparable {
    private SystemArticleManager systemArticleManager;
    private List systemArticles;
    private SystemArticle systemArticle;
    private Long  articleId;

    public void setSystemArticleManager(SystemArticleManager systemArticleManager) {
        this.systemArticleManager = systemArticleManager;
    }

    public List getSystemArticles() {
        return systemArticles;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String systemArticleId = getRequest().getParameter("systemArticle.articleId");
            if (systemArticleId != null && !systemArticleId.equals("")) {
                systemArticle = systemArticleManager.get(new Long(systemArticleId));
            }
        }
    }

    public String list() {
        systemArticles = systemArticleManager.getAll();
        return SUCCESS;
    }

    public void setArticleId(Long  articleId) {
        this. articleId =  articleId;
    }

    public SystemArticle getSystemArticle() {
        return systemArticle;
    }

    public void setSystemArticle(SystemArticle systemArticle) {
        this.systemArticle = systemArticle;
    }

    public String delete() {
        systemArticleManager.remove(systemArticle.getArticleId());
        saveMessage(getText("systemArticle.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (articleId != null) {
            systemArticle = systemArticleManager.get(articleId);
        } else {
            systemArticle = new SystemArticle();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (systemArticle.getArticleId() == null);

        systemArticleManager.save(systemArticle);

        String key = (isNew) ? "systemArticle.added" : "systemArticle.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}